package com.lyrcsoft.rokectmq.ordermessage;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author fujc2dev@126.com
 * @date 2024-05-09 16:04
 */
public class ProducerInOrder {
    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {
        DefaultMQProducer producer = new DefaultMQProducer("producer_group");
        producer.setNamesrvAddr("10.20.200.144:9876");
        producer.start();
        List<Order> orderList = Order.getOrderList();
        String[] tags = new String[]{
                "TagA", "TagB", "TagC"
        };
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateFormat.format(date);
        for (int i = 0; i < orderList.size(); i++) {
            String body = dateStr + "Order:" + orderList.get(i);
            Message m = new Message("PartOrder", tags[i % tags.length], "KEY" + i, body.getBytes(RemotingHelper.DEFAULT_CHARSET));
            SendResult sendResult = producer.send(m, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    Long id = (Long) arg;
                    Integer index = Math.toIntExact(id % mqs.size());
                    return mqs.get(index);
                }
            }, orderList.get(i).getOrderId());
            System.out.println(String.format("SendResult status: %s queueId:%d,body:%s",
                    sendResult.getMsgId(),
                    sendResult.getMessageQueue().getQueueId(),
                    body));
        }
        producer.shutdown();

    }
}
